import web
import tinyORM as db

'''
Defining models class for Webpy
'''


class Group(db.Model):
    '''
    Group entity subclassing base model (db.Model)
    '''
    _table = 'groups'

    '''
    Fields definitions
    '''
    id = db.Serial(primary_key=True)
    owner_id = db.Integer()
    name = db.String()
    description = db.String()

    '''
    Create new group in datastore
    @name is required
    '''
    def create(self, name, **kwargs):

        self.owner_id = '0'

        self.name = name

        if 'description' in kwargs:
            self.description = kwargs['description']

        obj = self.getById(self.put())
        return {'id': obj.id, 'name': web.net.websafe(obj.name), 'description': web.net.websafe(obj.description)}

    '''
    Removing group from datastore
    '''
    def remove(self):
        self.delete()

    '''
    Update informations of a group entity in datastore
    '''
    def update(self, **kwargs):

        if 'name' in kwargs:
            self.name = kwargs['name']

        if 'description' in kwargs:
            self.description = kwargs['description']

        self.put()

    '''
    Fecth a group entity by is Numeric ID
    '''
    def getById(self, id):
        user_id = 0
        obj = Group(int(id))

        if obj and obj.owner_id == user_id:
            return obj

        return None

    '''
    Fetch all groups for the current logged user
    '''
    def getAllByCurrentUser(self):

        user_id = 0

        dataset = Group.select(where='owner_id = $owner_id', order="name", vars={'owner_id': user_id})

        if dataset:
            results = []

            for obj in dataset:
                results.append({'id': obj.id, 'name': web.net.websafe(obj.name), 'description': web.net.websafe(obj.description)})

            return results
        else:
            return None


class Host(db.Model):
    '''
    Host entity subclassing base model (db.Model)
    '''
    _table = 'hosts'

    '''
    Fields definitions
    '''
    id = db.Serial(primary_key=True)
    owner_id = db.Integer()
    group_id = db.Integer()
    hostname = db.String()
    tunnel_status = db.String()
    tunnel_key = db.String()
    gateway_host = db.String()
    gateway_port = db.Integer()
    gateway_user = db.String()
    authorized_ip = db.String()
    lastcheck = db.Integer()
    log = db.String()

    '''
    Create new host in datastore
    @host is required
    @hostname is required
    '''
    def create(self, group_id, **kwargs):

        self.owner_id = 0
        self.group_id = group_id
        self.setProperties(**kwargs)

        obj = self.getById(self.put())
        return obj

    '''
    Removing host from datastore
    '''
    def remove(self):
        self.delete()

    '''
    Update informations of a host entity in datastore
    '''
    def update(self, **kwargs):
        self.setProperties(**kwargs)
        self.put()

    '''
    Fecth a host entity by is Numeric ID
    '''
    def getById(self, id):
        user_id = 0
        obj = Host(int(id))

        if obj and obj.owner_id == user_id:
            return obj

        return None

    '''
    Fetch all hosts for the current logged user
    '''
    def getAllByCurrentUser(self):

        user_id = 0

        dataset = Host.select(where='owner_id = $owner_id', order="hostname", vars={'owner_id': user_id})

        if dataset:
            results = []

            for obj in dataset:
                results.append({
                'id': obj.id,
                'group_id': obj.group_id,
                'hostname': web.net.websafe(obj.hostname),
                'tunnel_status': obj.tunnel_status,
                'tunnel_key': obj.tunnel_key,
                'gateway_user': web.net.websafe(obj.gateway_user),
                'gateway_port': web.net.websafe(obj.gateway_port),
                'gateway_host': web.net.websafe(obj.gateway_host),
                'authorized_ip': web.net.websafe(obj.authorized_ip),
                'lastcheck': obj.lastcheck,
                'log': obj.log
                })

            return results

        else:
            return None

    '''
    Fetch all hosts for the specified group_id
    '''
    def getAllByGroupId(self, group_id):

        #user_id = 0

        dataset = Host.select(where='group_id = $group_id', vars={'group_id': group_id})

        return dataset

    '''
    Fetch one host by tunnel_key
    '''
    def getByTunnelKey(self, tunnel_key):
        dataset = Host.select(where='tunnel_key = $tunnel_key', vars={'tunnel_key': tunnel_key})

        return dataset

    '''
    Setting host entity properties
    '''
    def setProperties(self, **kwargs):

        if 'hostname' in kwargs:
            self.hostname = kwargs['hostname']

        if 'tunnel_status' in kwargs:
            self.tunnel_status = kwargs['tunnel_status'].upper()

        if 'tunnel_key' in kwargs:
            self.tunnel_key = kwargs['tunnel_key']

        if 'gateway_host' in kwargs:
            self.gateway_host = kwargs['gateway_host']

        if 'gateway_port' in kwargs:
            self.gateway_port = kwargs['gateway_port']

        if 'gateway_user' in kwargs:
            self.gateway_user = kwargs['gateway_user']

        if 'authorized_ip' in kwargs:
            self.authorized_ip = kwargs['authorized_ip']

        if 'lastcheck' in kwargs:
            self.lastcheck = kwargs['lastcheck']

        if 'log' in kwargs:
            self.log = kwargs['log']
